/**
 * 
 */
package pers.vic.test.delay;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * @description: java 延迟队列测试
 * @author Vic.xu
 * @date: 2021年4月14日下午2:55:11
 */
public class DelayTask implements Delayed {

	private long startDate;

	/**
	 * @param startDate
	 */
	public DelayTask(long startDate) {
		super();
		this.startDate = startDate;
	}

	@Override
	public int compareTo(Delayed o) {
		return Long.compare(this.getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS));
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return this.startDate - System.currentTimeMillis();
	}
	
	private void print() {
		System.out.println("startDate: " + startDate);
	}

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<DelayTask> queue = new DelayQueue<DelayTask>();
		DelayTask delayTask = new DelayTask(1000 * 2L + System.currentTimeMillis());
		queue.put(delayTask);
		DelayTask delayTask2 = new DelayTask(1000 * 10L + System.currentTimeMillis());
		queue.put(delayTask2);
		printNow();
		
		while (queue.size() > 0) {
			queue.take().print();;
			printNow();
		}

	}

	public static void printNow() {
		System.out.println(System.currentTimeMillis() + " " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
	}

}
